package managers;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

import mine.activity.FunctionActivity;

import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

import peishui.activities.GateActivity;
import peishui.activities.PeiShuiActivity;
import peishui.network.http.GetRealCannelDam;
import shuiyuqing.activities.WaterActivity;
import shuiyuqing.fragments.WaterFragment;
import shuiyuqing.fragments.WeatherFragment;
import shuiyuqing.network.beans.IrrBAWaterGate;
import shuiyuqing.network.beans.IrrBMSystem;
import shuiyuqing.network.beans.IrrBRMeteorological;
import shuiyuqing.network.beans.IrrBRRain;
import shuiyuqing.network.beans.RealTimeIrrBRWaterDam;
import shuiyuqing.network.http.GetRainWeather;
import shuiyuqing.network.http.GetRealWaterGateDam;
import utils.CommonUtil;
import utils.TimeUtil;

/**
 * 统一控制UI
 * Created by 凯 on 2015/10/18.
 */
public class UIHandler extends Handler {
    public static UIHandler uiHandler;

    private Context context;

    // 界面
    private HashMap<String, Activity> uis = new HashMap<String, Activity>();

    // 服务
    private HashMap<String, Service> services = new HashMap<String, Service>();


    //　通过名字获取到界面
    public Activity getActivityByName(String name) {
        return uis.get(name);
    }

    public UIHandler() {
        super();
        context = MyApplication.share();
    }

    // 通过名字获取服务
    public Service getServiceByName(String name) {
        return services.get(name);
    }

    /**
     * 界面注册
     *
     * @param name
     * @param ui
     */
    public void register(String name, Activity ui) {
        uis.put(name, ui);
    }

    /**
     * 界面反注册
     *
     * @param name
     * @param ui
     */
    public void unregister(String name, Activity ui) {
        uis.remove(name);
    }


    /**
     * 服务注册
     *
     * @param name
     * @param service
     */
    public void register(String name, Service service) {
        services.put(name, service);
    }

    /**
     * 服务反注册
     *
     * @param name
     * @param service
     */
    public void unregister(String name, Service service) {
        services.remove(name);
    }

    // 界面修改部分
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);


        WaterActivity waterActivity = (WaterActivity) uis.get(WaterActivity.class.getSimpleName());
        PeiShuiActivity peiShuiActivity = (PeiShuiActivity) uis.get(PeiShuiActivity.class.getSimpleName());
        GateActivity gateActivity = (GateActivity) uis.get(GateActivity.class.getSimpleName());
        FunctionActivity functionActivity = (FunctionActivity) uis.get(FunctionActivity.class.getSimpleName());


        switch (msg.what) {

            // 下面的是水雨情的,和闸门信息查看的
            case 0x50:
                if (waterActivity != null) {
                    GetRealWaterGateDam dam = (GetRealWaterGateDam) msg.obj;
                    WaterFragment fragment = waterActivity.getWaterFragment();
                    fragment.clear();

                    RealTimeIrrBRWaterDam dam1 = dam.getDownload().getRealTimeIrrBRWaterDam();
                    if (dam1 != null) {
                        fragment.setRealTimeIrrBRWaterDam(dam1);
                        fragment.getTv_upLevel().setText(dam1.getHeightUp() + "");
                        fragment.getTv_downLevel().setText(dam1.getHeightDown() + "");
                        fragment.getTv_flow().setText(dam1.getFluxGate() + "");

                        setGateHeight(fragment.getTv_open1(), dam1.getOpenDegree1());
                        setGateHeight(fragment.getTv_open2(), dam1.getOpenDegree2());
                        setGateHeight(fragment.getTv_open3(), dam1.getOpenDegree3());
                        setGateHeight(fragment.getTv_open4(), dam1.getOpenDegree4());
                        setGateHeight(fragment.getTv_open5(), dam1.getOpenDegree5());


                        fragment.getTv_openDot().setText(dam1.getGateOpenCount() + "");

                        String str_gateState = dam1.getGateState().trim();
                        if (str_gateState != null && str_gateState.length() > 0) {

                            WaterFragment.setGateState(fragment.getTv_open1(), str_gateState.charAt(0));
                            WaterFragment.setGateState(fragment.getTv_open2(), str_gateState.charAt(1));
                            WaterFragment.setGateState(fragment.getTv_open3(), str_gateState.charAt(2));
                            WaterFragment.setGateState(fragment.getTv_open4(), str_gateState.charAt(3));
                            WaterFragment.setGateState(fragment.getTv_open5(), str_gateState.charAt(4));


                        }

                        if (TimeUtil.isToday(dam1.getMeaTime()))
                        {
                            fragment.getTv_date().setTextColor(Color.parseColor("#FFA500"));
                            fragment.getTv_time().setTextColor(Color.parseColor("#FFA500"));
                        }
                        else
                        {
                            fragment.getTv_date().setTextColor(Color.parseColor("#D3D3D3"));
                            fragment.getTv_time().setTextColor(Color.parseColor("#D3D3D3"));
                        }

                        fragment.getTv_time().setText(TimeUtil.timestamp2time(dam1.getMeaTime().getTimeInMillis()));
                        fragment.getTv_date().setText(TimeUtil.timestamp2Date(dam1.getMeaTime().getTimeInMillis()));
                        // 设计水位与实际水位部分
                        if (waterActivity.getIrrBAWaterGate() != null) {

                            // 显示
                            fragment.getV_bars().setVisibility(View.VISIBLE);
                            View v_design = fragment.getV_design();
                            TextView tv_design = fragment.getTv_designLevel();
                            TextView tv_real = fragment.getTv_realLevel();

                            IrrBAWaterGate gate = waterActivity.getIrrBAWaterGate();
                            String bd_design = gate.getDesignWaterLevel();
                            BigDecimal bd_real = dam1.getHeightUp();
                            fragment.getTv_gangcheng().setText(gate.getFloorElevation().setScale(2,BigDecimal.ROUND_HALF_UP)+"");


                            int height = fragment.getDesignHeight();
                            if (bd_real != null && bd_design != null) {
                                double percent = bd_real.doubleValue() / Double.parseDouble(bd_design);
                                int real_height = (int) (height * percent);

                                View v_realLevel = fragment.getV_realLevel();
                                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) v_realLevel.getLayoutParams();
                                params.setMargins(0, height - real_height, 0, 0);
                                v_realLevel.setLayoutParams(params);

                                tv_design.setText(waterActivity.getIrrBAWaterGate().getWatergateQ() + "");

                                tv_real.setText(bd_real + "");
                                RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams) tv_real.getLayoutParams();
                                int margin_top = 0;
                                if (height - real_height < DensityUtil.px2dip(MyApplication.share(), 48)) {
                                    margin_top = DensityUtil.px2dip(MyApplication.share(), 48);
                                } else {
                                    margin_top = height - real_height;
                                }
                                params1.setMargins(0, margin_top, 0, 0);
                                tv_real.setLayoutParams(params1);


                                // 若实际水位大于设计水位
                                if (bd_real.doubleValue() - Double.parseDouble(bd_design) > 0) {
                                    fragment.getTv_upLevel().setTextColor(Color.RED);
                                } else {
                                    fragment.getTv_upLevel().setTextColor(Color.parseColor("#0099FF"));
                                }
                            }


                        }

                        fragment.getNoneInfo().setVisibility(View.GONE);
                    }
                    else
                    {
                        fragment.getNoneInfo().setVisibility(View.VISIBLE);

                    }

                    IrrBMSystem system = dam.getDownload().getIrrBMSystem();
                    if (system != null) {

                        // 清空照片前进栈
                        fragment.getStack().clear();

                        // 查看最新的照片信息

                        // 保存照片信息
                        fragment.setIrrBMSystem(system);

                        // 获取最新的照片
                        String IP = MyApplication.share().getResources().getString(R.string.serverIp);
                        String url = "http://" + IP + "/xingkaih/" + VolleySingleton.encodeUrl(system.getFileName());
                        if (fragment.getBitmap() != null) {
                            fragment.getBitmap().recycle();
                        }
                        ImageLoader.getInstance().displayImage(url, fragment.getImg_img(), MyApplication.options);

                    } else {

                    }

                }

                if (gateActivity != null) {

                    WaterFragment fragment = waterActivity.getWaterFragment();

                    GetRealWaterGateDam realWaterGateDam = (GetRealWaterGateDam) msg.obj;
                    IrrBMSystem system = realWaterGateDam.getDownload().getIrrBMSystem();

                    if (system != null) {
                        String IP = MyApplication.share().getResources().getString(R.string.serverIp);
                        String url = "http://" + IP + "/xingkaih/" + VolleySingleton.encodeUrl(system.getFileName());
                        ImageLoader.getInstance().displayImage(url, fragment.getImg_img(), MyApplication.options);
                    }
                    gateActivity.initviewWithdata(null, realWaterGateDam.getDownload().getRealTimeIrrBRWaterDam());
                }

                break;

            // 设置图片
            case 0x51:
                if (waterActivity != null) {

                    WaterFragment fragment = waterActivity.getWaterFragment();
                    fragment.setBitmap((Bitmap) msg.obj);
                    fragment.getImg_img().setImageBitmap((Bitmap) msg.obj);

                }

                if (gateActivity != null) {
                    gateActivity.getImg_img().setImageBitmap((Bitmap) msg.obj);

                }

                break;

            // 设置气象
            case 0x52:
                if (waterActivity != null) {
                    waterActivity.getWeatherFragment().clear();
                    GetRainWeather weather = (GetRainWeather) msg.obj;

                    List<IrrBRMeteorological> irrBRMeteorologicals = weather.getDownload().getBrMeteorologicals();
                    List<IrrBRRain> rains = weather.getDownload().getBrRains();
                    WeatherFragment fragment = waterActivity.getWeatherFragment();


                    if (!rains.isEmpty()) {
                        IrrBRRain rain = rains.get(0);
                        fragment.getTv_rainTime().setText(TimeUtil.getTimeByDate2(rain.getMeaTime().getTime()));
                        fragment.getTv_rainValue().setText(rain.getP() + "");
                        if (TimeUtil.isToday(rain.getMeaTime()))
                        {
                            fragment.getTv_rainTime().setTextColor(Color.parseColor("#FFA500"));
                        }
                        else
                        {
                            fragment.getTv_rainTime().setTextColor(Color.parseColor("#D3D3D3"));
                        }

                    }

                    if (!irrBRMeteorologicals.isEmpty()) {
                        IrrBRMeteorological irrBRMeteorological = irrBRMeteorologicals.get(0);
                        fragment.getTv_humidity().setText(irrBRMeteorological.getHumidity() + "");
                        fragment.getTv_temperature().setText(irrBRMeteorological.getTemperature() + "");

                        fragment.getTv_winddir().setText(CommonUtil.flow2StrName(Double.parseDouble(irrBRMeteorological.getWindDir().trim())));
                        fragment.getTv_windspeed().setText(irrBRMeteorological.getWindSpeed() + "");

                        fragment.setInfo(irrBRMeteorological);
                    }

//                    waterActivity.getV_refresh().setVisibility(View.GONE);

                }
                break;
            // 设置界面
            case 0x54:
                if (peiShuiActivity != null) {
                    GetRealCannelDam dam = (GetRealCannelDam) msg.obj;
                    peiShuiActivity.getAdapter().setDam(dam);
                    peiShuiActivity.getAdapter().notifyDataSetChanged();
                }
                break;
        }

    }


    // 设置闸高
    public void setGateHeight(TextView tv, BigDecimal str) {
//        System.out.println(str);
        if (str.compareTo(new BigDecimal(0)) < 0) {
            tv.setText("!");
        } else if (str.equals(null)) {
            tv.setText("--");
        } else {
            tv.setText(str + "");
        }
    }

    // 退出所有的界面
    public void finishiall() {
        for (Activity activity : uis.values()) {
            activity.finish();
        }
    }

    // 除了某节目外退出其他界面
    public void finishallbut(Activity target) {
        for (Activity activity : uis.values()) {
            if (activity != target) {
                activity.finish();
            }
        }
    }

    // 通过名称获取activity
    public Activity getactbyName(String name) {
        return uis.get(name);
    }


    public static interface UIAdapter {
        public String simpleName();
    }

    /**
     * 协助控制类
     */
    public static class BaseActivity extends FragmentActivity implements UIAdapter {

        ProgressDialog pdg;

        public ProgressDialog getPdg() {
            return pdg;
        }

        public void showDialog() {
            pdg.show();
            pdg.setContentView(R.layout.window_progress);
//            pdg.setCancelable(false);
        }

        public void closeDialog() {
            pdg.dismiss();
        }

        @Override
        public String simpleName() {
            return this.getClass().getSimpleName();
        }

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            pdg = new ProgressDialog(this);

            UIHandler.uiHandler.register(simpleName(), this);

        }

        @Override
        protected void onStart() {
            super.onStart();
            Button btn_back = (Button) findViewById(R.id.id_btn_back);
            if (btn_back == null) return;
            btn_back.setText(MyApplication.share().getResources().getString(R.string.back));
            btn_back.setBackgroundColor(Color.parseColor("#00000000"));
            btn_back.setTypeface(MyApplication.iconfont);
            btn_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            UIHandler.uiHandler.unregister(simpleName(), this);
        }
    }

    /**
     * 基本控制服务
     */
    public static class BaseService extends Service {

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate() {
            super.onCreate();
            UIHandler.uiHandler.register(this.getClass().getSimpleName(), this);
        }

        @Override
        public void onDestroy() {
            super.onDestroy();
            UIHandler.uiHandler.unregister(this.getClass().getSimpleName(), this);
        }
    }
}
